package com.example.zookeeperdemo;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.StandardCharsets;

public class ZookeeperUtils {
    public static CuratorFramework getClient(String host, int port) {
        String zookeeperConnectionString = host + ":" + port;
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
        client.start();
        return client;
    }

    public static void creatNode(CuratorFramework client, String nodePath, String data) throws ZookeeperOperationException {
        try {
            client.create().forPath(nodePath, data.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new ZookeeperOperationException(String.format("创建节点[%s]失败，data=[%s]", nodePath, data), e);
        }
    }

    public static void deleteNode(CuratorFramework client, String nodePath) throws ZookeeperOperationException {
        try {
            client.delete().forPath(nodePath);
        } catch (Exception e) {
            throw new ZookeeperOperationException(String.format("删除节点[%s]失败", nodePath), e);
        }
    }

    public static void setNodeData(CuratorFramework client, String nodePath, String data) throws ZookeeperOperationException {
        try {
            client.setData().forPath(nodePath, data.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new ZookeeperOperationException(String.format("设置节点[%s]数据失败，data=[%s]", nodePath, data), e);
        }
    }

    public static boolean existNode(CuratorFramework client, String nodePath) throws ZookeeperOperationException {
        try {
            return client.checkExists().forPath(nodePath) != null;
        } catch (Exception e) {
            throw new ZookeeperOperationException(String.format("判断节点[%s]是否存在失败", nodePath), e);
        }
    }
}
